package org.example.javafxdemo;

import com.app.common.MarkdownUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MarkdownPreviewController {

    @FXML
    private TextArea inputTextArea;

    @FXML
    private VBox inputVBox;

    @FXML
    private BorderPane mainBorderPane;

    @FXML
    private WebView outputWebView;

    @FXML
    private void initialize() {
        // 添加用户样式
        //outputWebView.getEngine().setUserStyleSheetLocation(getClass().getResource("css/colour-messages.css").toExternalForm());
        outputWebView.getEngine().setUserStyleSheetLocation(getClass().getResource("css/vue.css").toExternalForm());

        WebEngine webEngine = outputWebView.getEngine();
        inputTextArea.textProperty().addListener((observable, oldValue, newValue) -> updateWebView());
        // 初始 load 本地文件
        initLoad();

        updateWebView();

        // 设置VBox的宽度为50%
        double halfWidth = mainBorderPane.getWidth() / 2;
        inputVBox.setPrefWidth(halfWidth);
        //inputVBox.setPrefHeight(mainBorderPane.getHeight());
        //inputTextArea.setMaxHeight(inputVBox.getHeight());

        // 监听窗口尺寸变化
        mainBorderPane.widthProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                double halfWidth = newValue.doubleValue() / 2;
                inputVBox.setPrefWidth(halfWidth);
            }
        });
    }

    private void updateWebView() {
        String markdownText = inputTextArea.getText();
        String htmlContent = MarkdownUtil.parseMarkdownToHtml(markdownText);
        outputWebView.getEngine().loadContent(htmlContent);
    }

    private void initLoad() {
        try (BufferedReader reader = new BufferedReader(new FileReader("note.md"))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            inputTextArea.setText(content.toString());
            outputWebView.getEngine().loadContent(MarkdownUtil.parseMarkdownToHtml(content.toString()));
            //previewArea.getCssMetaData()
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
